import { Message } from "element-ui";
import _ from "lodash";

const SUCCESS = "success";
const WARNING = "warning";
const INFO = "info";
const ERROR = "error";

let instance;

class MessagerConstructor {
  constructor() {
    this.instanceIds = [];
  }
  length() {
    return this.instanceIds.length;
  }
  isOver() {
    return this.length() >= process.env.VUE_APP_MESSAGER_LIMIT;
  }
  show(options, single) {
    let self = this;
    let onClose = ({ id }) => {
      if (options.onClose) {
        options.onClose();
      }
      this.instanceIds.splice(this.instanceIds.indexOf(id), 1);
    };
    let msginstance;
    if (single) {
      if (process.env.VUE_APP_MESSAGER_LOG) {
        switch (options.type) {
          case SUCCESS:
            console.info(options.message);
            break;
          case WARNING:
            console.warn(options.message);
            break;
          case INFO:
            console.info(options.message);
            break;
          case ERROR:
            console.error(options.message);
            break;
          default:
        }
      }
      if (this.isOver()) {
        let id = this.instanceIds.shift();
        Message.close(id);
      }
      msginstance = Message({ ...options, onClose: onClose });
      this.instanceIds.push(msginstance.id);
    } else {
      msginstance = Message({ ...options, onClose: onClose });
      this.instanceIds.push(msginstance.id);
    }
  }
}

const Messager = function(_options, single = true) {
  let options = _options || {};
  if (!instance) {
    instance = new MessagerConstructor();
  }
  instance.show(options, single);
};

[SUCCESS, WARNING, INFO, ERROR].forEach(type => {
  Messager[type] = (_options, single = true) => {
    let options = _.cloneDeep(_options);
    if (typeof options === "string") {
      options = {
        message: options
      };
    }
    options.type = type;
    return Messager(options, single);
  };
});

export default Messager;
